package com.smallkingson.ylib.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class YSQLiteOpenHelper extends SQLiteOpenHelper {

	private static YSQLiteOpenHelper helper;

	private static int version = 1;// 版本

	private List<SQLiteOpenHelperListener> helperListeners;

	public static YSQLiteOpenHelper getInstance(Context context) {

		if (helper == null) {
			synchronized (YSQLiteOpenHelper.class) {
				if (helper == null) {
					helper = new YSQLiteOpenHelper(context, "YDB.db", null,
							version);
				}
			}
		}
		return helper;
	}

	public void addSQLiteOpenHelperListener(SQLiteOpenHelperListener listener) {
		helperListeners.add(listener);
	}

	public void removeSQLiteOpenHelperListener(SQLiteOpenHelperListener listener) {
		helperListeners.remove(listener);
	}

	public YSQLiteOpenHelper(Context context, String name,
							 CursorFactory factory, int version) {
		super(context, name, factory, version);
		helperListeners = new ArrayList<SQLiteOpenHelperListener>();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		for (SQLiteOpenHelperListener l : helperListeners) {
			l.onCreate(db);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int o, int n) {
		for (SQLiteOpenHelperListener l : helperListeners) {
			l.onUpgrade(db, o, n);
		}
	}

	public static int getVersion() {
		return version;
	}

	public static void setVersion(int version) {
		YSQLiteOpenHelper.version = version;
	}

	public static interface SQLiteOpenHelperListener {
		void onCreate(SQLiteDatabase db);

		void onUpgrade(SQLiteDatabase db, int o, int n);
	}
}
